package autoschedule;

import java.io.*;
import java.util.*;
import javax.swing.text.*;

import controller.RSMSController;

import autoteam.Local;

import jxl.*;
import jxl.write.*;

import alarm.*;

/**
 * This is the Document part of the basic Document-View model used in this
 * program. The AutoScheduleDoc object holds all data-containing objects.
 */

public class AutoScheduleDoc extends Observable implements Serializable
{
    // The name variable is used when generating filenames.
    String name = null;
    
    /**
     * A flag. This determines whether or not files are time-stamped.
     */
    boolean bTimeStamp = true;
    
    /**
     * A flag. This determines whether or not files are version-stamped.
     */
    boolean bFileVersion = true;
    
    /**
     * The current version number (when writing files). This is only incremented
     * when the schedule is saved.
     */
    int FileVersion = 0;
    /**
     * Control used for finding the Current User and Current Sport
     */
    RSMSController control;
    
    public static final int ADD = 0;
    public static final int DEL = 1;
    public static final int RENAME = 2;
    public static final int SCHEDULE_CHANGED = 3;
    public static final int SCHEDULE_SWITCH_ERROR = 4;
    
    /**
     * Holds the list of Leagues being scheduled.
     * 
     * @see autoschedule.League
     */
    Vector leagues = null;
    
    /**
     * Holds the list of Facilities being scheduled.
     * 
     * @see autoschedule.League
     */
    Vector facilities = null;
    
    /**
     * Used only for serialization Before serializing, this string is filled
     * with the text contained in logDocument
     */
    String logString = null;
    
    transient DefaultStyledDocument logDocument = null;
    
    /**
     * The source file. We remember it so that we know where to save to.
     */
    File sourceFile = null;
    
    public File getSourceFile()
    {
	return sourceFile;
    }
    
    public void setSourceFile(File f)
    {
	sourceFile = f;
	name = f.getName();
    }
    
    /**
     * Write this AutoScheduleDoc to a file using streaming. The extension is
     * automatically set to ".auto"
     */
    
    public void saveDoc(File f)
    {
	try
	{
	    FileOutputStream out1 = null;
	    if (f != null)
		out1 = new FileOutputStream(f);
	    else
		out1 = new FileOutputStream(name + ".auto");
	    FileVersion++;
	    
	    ObjectOutputStream s = new ObjectOutputStream(out1);
	    s.writeObject(this);
	    s.flush();
	    
	}
	catch (Exception e)
	{
	    ;
	}
    }
    
    public void toggleUseTimeStamp()
    {
	bTimeStamp = (bTimeStamp ? false : true);
    }
    
    public boolean getUseTimeStamp()
    {
	return bTimeStamp;
    }
    
    public void toggleUseFileVersion()
    {
	bFileVersion = (bFileVersion ? false : true);
    }
    
    public boolean getUseFileVersion()
    {
	return bFileVersion;
    }
    
    public int getFileVersion()
    {
	return FileVersion;
    }
    
    /**
     * A utility to generate a time-stamp for files.
     */
    
    public String getTimeStamp()
    {
	String s = "";
	
	if (bTimeStamp)
	{
	    java.text.NumberFormat formatter = java.text.NumberFormat.getInstance();
	    formatter.setMinimumIntegerDigits(2);
	    
	    Calendar cal = Calendar.getInstance();
	    s += "_";
	    s += cal.get(cal.YEAR);
	    s += formatter.format((double) (cal.get(cal.MONTH) + 1));
	    s += formatter.format((double) (cal.get(cal.DAY_OF_MONTH)));
	}
	if (bFileVersion)
	{
	    s += "_";
	    s += FileVersion;
	}
	return s;
    }
    
    /**
     * Write the current schedule to a single HTML. The format consists of a
     * table of contents with links to each team. The team schedules are listed
     * one by one in the body of the file. The directory is currently set to the
     * user.dir and the file name hardcoded to schedule.html
     */
    
    public void writeSchedule()
    {
	String dir = System.getProperty("user.dir");
	try
	{
	    File f = new File(dir, "schedule" + getTimeStamp() + ".html");
	    f.createNewFile();
	    BufferedWriter out = new BufferedWriter(new FileWriter(f));
	    
	    out.write("<html>");
	    out.newLine();
	    out.write("<head>");
	    out.newLine();
	    out.write("<title>");
	    out.newLine();
	    out.write("BSA Schedule");
	    out.newLine();
	    out.write("</title>");
	    out.newLine();
	    out.write("<meta name=\"description\" content=\"\">");
	    out.newLine();
	    out.write("<meta name=\"keywords\" content=\"\">");
	    out.newLine();
	    out.write("</head>");
	    out.newLine();
	    out
	       .write("<body bgcolor=\"#00CCFF\" text=\"#000000\" link=\"#0000FF\" vlink=\"#FF00FF\" background=\"\">");
	    out.newLine();
	    out.write("<div align=\"center\">");
	    out.newLine();
	    out.write("<a name=top><h1> BSA Schedule</h1></a>");
	    out.newLine();
	    out.write("Updated: " + Local.format(new Date()) + "<br><br>");
	    out.newLine();
	    out.write("</div>");
	    out.newLine();
	    out.write("<h2>Contents</h2>");
	    out.newLine();
	    int count = 0;
	    for (Iterator I = leagues.iterator(); I.hasNext();)
	    {
		League l = (League) I.next();
		out.write("<b>League " + l.getName() + "</b> : ");
		
		for (Iterator J = l.allTeams.iterator(); J.hasNext();)
		{
		    Team t = (Team) J.next();
		    out.write("<a href=\"#" + t.toString() + "\"> " + t.toString() + "</a>    ");
		}
		out.write("<br>");
		out.newLine();
	    }
	    out.write("<hr>");
	    out.newLine();
	    for (Iterator I = leagues.iterator(); I.hasNext();)
	    {
		League l = (League) I.next();
		writeLeagueSchedule(l, out);
	    }
	    
	    out.write("</body><br></html>");
	    
	    out.close();
	    
	}
	catch (IOException e)
	{
	    System.out.println(e);
	}
	
    }
    
    void writeLeagueSchedule(League l, BufferedWriter out) throws IOException
    {
	out.write("<h2>League " + l.getName() + "</h2><br>");
	out.newLine();
	
	for (Iterator J = l.allTeams.iterator(); J.hasNext();)
	{
	    Team t = (Team) J.next();
	    out.write("<b><a name=" + t.toString() + "> Team " + t.toString() + "</a></b><br>");
	    for (Iterator K = l.games.iterator(); K.hasNext();)
	    {
		Game g = (Game) K.next();
		if (!g.involves(t))
		    continue;
		out.write(g.toString());
		out.write("<br>");
		out.newLine();
	    }
	    out.write("<a href=\"#top\">Return to top</a><br><br>");
	    out.newLine();
	}
	out.write("<br><hr>");
	out.newLine();
    }
    
    public void addGame(League l)
    {
	Game g = new Game();
	System.out.println(g);
	System.out.println(l);
	g.league = l;
	System.out.println(l.games);
	l.games.add(g);
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, g.league));
	this.addGameToAlarmSystem(g);
    }
    
    public void createInterleagueTeam(String teamName, Game g, League league, int position)
    {
	Team t = new Team(-1, league);
	t.name = teamName;
	t._isInterLeague = true;
	league.interLeagueTeams.add(t);
	g.setTeam(position, t);
    }
    
    public void deleteGame(Game g)
    {
	this.removeGameFromAlarmSystem(g);
	g.remove();
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, g.league));
	
    }
    
    public void unScheduleGame(Game g)
    {
	this.removeGameFromAlarmSystem(g);
	g.unSchedule();
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, g.league));
    }
    
    public void moveGameLater(Game g)
    {

    }
    
    public void deleteFacilityAvailability(Facility facility, int row)
    {
	facility.killBlock(row);
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, null));
    }
    
    public void switchGames(Game g1, Game g2)
    {
	// are these games scheduled?
	
	if (!g1.isScheduled() || !g2.isScheduled())
	{
	    System.out.println("isScheduled mismatch");
	    setChanged();
	    notifyObservers(new ScheduleMsg(SCHEDULE_SWITCH_ERROR, g1.league));
	    return;
	}
	
	// are these consecutive?
	if (g1.facility == g2.facility)
	    System.out.println(" Are consecutive = " + g1.facility.areConsecutiveGames(g1, g2));
	
	// are the durations the same or are these consecutive?
	
	int d1 = (int) (60 * g1.league.hrsPerGame.doubleValue());
	int d2 = (int) (60 * g2.league.hrsPerGame.doubleValue());
	if (d1 != d2)
	{
	    System.out.println("durations mismatch");
	    setChanged();
	    notifyObservers(new ScheduleMsg(SCHEDULE_SWITCH_ERROR, g1.league));
	    return;
	}
	
	// are the capacity requirements the same?
	int d12 = ((Integer) g1.league.facilityCapacity.get(g2.facility)).intValue();
	int d11 = ((Integer) g1.league.facilityCapacity.get(g1.facility)).intValue();
	int d21 = ((Integer) g2.league.facilityCapacity.get(g1.facility)).intValue();
	int d22 = ((Integer) g2.league.facilityCapacity.get(g2.facility)).intValue();
	if ((d11 != d12) || (d21 != d22))
	{
	    setChanged();
	    notifyObservers(new ScheduleMsg(SCHEDULE_SWITCH_ERROR, g1.league));
	    return;
	}
	this.removeGameFromAlarmSystem(g1);
	this.removeGameFromAlarmSystem(g2);
	g1.switchWith(g2);
	this.addGameToAlarmSystem(g1);
	this.addGameToAlarmSystem(g2);
	
	appendToLog("Game " + g1.toString() + " switched with game " + g2.toString());
	
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, g1.league));
    }
    
    public void scheduleGame(Game g, Facility f, Day d)
    {
	if (g.isScheduled())
	    unScheduleGame(g);
	f.schedule(g, d, this);
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, g.league));
	return;
    }
    
    public void writeExcelSchedule() // File f)
    {
	// Collect references to all games
	Vector games = new Vector();
	
	String dir = System.getProperty("user.dir");
	try
	{
	    WritableWorkbook workbook = Workbook.createWorkbook(new File(dir, "schedule"
									      + getTimeStamp()
									      + ".xls"));
	    int count = 0;
	    for (Iterator I = leagues.iterator(); I.hasNext();)
	    {
		League l = (League) I.next();
		l.sortGames();
		
		WritableFont times12font = new WritableFont(WritableFont.TIMES, 12,
							    WritableFont.BOLD, true);
		WritableCellFormat times12format = new WritableCellFormat(times12font);
		
		WritableSheet sheet = workbook.createSheet("League " + l.getName(), count++);
		Label label = new Label(0, 0, "Date", times12format);
		sheet.addCell(label);
		label = new Label(1, 0, "Match", times12format);
		sheet.addCell(label);
		label = new Label(2, 0, "Time", times12format);
		sheet.addCell(label);
		label = new Label(3, 0, "Location", times12format);
		sheet.addCell(label);
		
		int row = 1;
		int DOY = -1;
		for (Iterator J = l.games.iterator(); J.hasNext();)
		{
		    Game g = (Game) J.next();
		    int d1 = g.getDayOfYear();
		    if (DOY != d1)
		    {
			row++;
			DOY = d1;
			
			if (g == null || g.getDate() == null)
			{
			    label = new Label(1, row, "???");
			    sheet.addCell(label);
			}
			else
			{
			    DateFormat customDateFormat = new DateFormat("dd MMM");
			    WritableCellFormat dateFormat = new WritableCellFormat(customDateFormat);
			    DateTime dateCell = new DateTime(0, row, g.getDate(), dateFormat);
			    sheet.addCell(dateCell);
			}
		    }
		    
		    label = new Label(1, row, g.getMatch());
		    sheet.addCell(label);
		    
		    label = new Label(2, row, (g.time == null ? "tbd" : g.time.toString()));
		    sheet.addCell(label);
		    
		    label = new Label(3, row, g.getFacilityName());
		    sheet.addCell(label);
		    
		    row++;
		}
	    }
	    workbook.write();
	    workbook.close();
	}
	catch (IOException e)
	{
	    System.out.println(e);
	}
	catch (jxl.write.WriteException e)
	{
	    System.out.println(e);
	}
	
    }
    
    public void writeFacilitySchedule()
    {
	// Collect references to all games
	Vector games = new Vector();
	for (Iterator I = leagues.iterator(); I.hasNext();)
	{
	    League l = (League) I.next();
	    for (Iterator K = l.games.iterator(); K.hasNext();)
	    {
		games.add(K.next());
	    }
	}
	Collections.sort(games, new Comparator()
	{
	    public int compare(Object o1, Object o2)
	    {
		if (o1 == o2)
		    return 0;
		Game g1 = (Game) o1;
		Game g2 = (Game) o2;
		
		int d1 = g1.getDayOfYear();
		int d2 = g2.getDayOfYear();
		
		int ret = (d1 < d2 ? -1 : (d1 == d2 ? 0 : 1));
		if (ret == 0)
		{
		    if (g1.getFacilityName() == g2.getFacilityName())
			ret = 0;
		    else
		    {
			if (g1.getFacilityName() == null)
			    ret = -1;
			else if (g2.getFacilityName() == null)
			    ret = 1;
			else
			    ret = g1.getFacilityName().compareTo(g2.getFacilityName());
		    }
		}
		
		if (ret == 0 && g1.time != null && g2.time != null)
		    ret = g1.time.compareTo(g2.time);
		if (ret == 0 && g1.time == null && g2.time != null)
		    return 1;
		if (ret == 0 && g1.time != null && g2.time == null)
		    return -1;
		
		return ret;
	    }
	});
	
	String dir = System.getProperty("user.dir");
	try
	{
	    File f = new File(dir, "facility_schedule" + getTimeStamp() + ".html");
	    f.createNewFile();
	    BufferedWriter out = new BufferedWriter(new FileWriter(f));
	    
	    System.out.println("Writing to " + f);
	    
	    out.write("<html>");
	    out.newLine();
	    out.write("<head>");
	    out.newLine();
	    out.write("<title>");
	    out.newLine();
	    out.write("BSA Facility Schedule");
	    out.newLine();
	    out.write("</title>");
	    out.newLine();
	    out.write("<meta name=\"description\" content=\"\">");
	    out.newLine();
	    out.write("<meta name=\"keywords\" content=\"\">");
	    out.newLine();
	    out.write("</head>");
	    out.newLine();
	    out
	       .write("<body bgcolor=\"#00CCFF\" text=\"#000000\" link=\"#0000FF\" vlink=\"#FF00FF\" background=\"\">");
	    out.newLine();
	    out.write("<div align=\"center\">");
	    out.newLine();
	    out.write("<a name=top><h1> BSA Schedule</h1></a>");
	    out.newLine();
	    out.write("Updated: " + Local.format(new Date()) + "<br><br>");
	    out.newLine();
	    out.write("</div>");
	    out.newLine();
	    
	    int DOY = -1;
	    // Facility oldFac = null;
	    String oldFac = null;
	    for (Iterator I = games.iterator(); I.hasNext();)
	    {
		Game g = (Game) I.next();
		if (g.getFacilityName() == null)
		    continue;
		int d1 = g.getDayOfYear();
		if (DOY == -1 || d1 != DOY)
		{
		    if (DOY != -1)
			out.write("</ul>");
		    out
		       .write("<hr><h2> "
			      + (g.getDate() == null ? "???" : Local.format(g.getDate())) + "</h2>");
		    out.newLine();
		    DOY = d1;
		}
		// if(!g.isFacility(oldFac))
		if (oldFac == null || !g.getFacilityName().matches(oldFac))
		{
		    if (oldFac != null)
		    {
			out.write("</ul><br>");
			out.newLine();
		    }
		    out.write("<ul> " + g.getFacilityName());
		    out.newLine();
		    oldFac = g.getFacilityName();
		    out.newLine();
		}
		out.write("<li>" + g.toLongString() + "</li>");
		out.newLine();
	    }
	    if (oldFac != null)
	    {
		out.write("</ul><br>");
		out.newLine();
	    }
	    
	    out.write("</body><br></html>");
	    
	    out.close();
	    
	}
	catch (IOException e)
	{
	    System.out.println(e);
	}
    }
    
    public File writeLog()
    {
	String dir = System.getProperty("user.dir");
	try
	{
	    File f = new File(dir, name + "_log" + ".txt");
	    f.createNewFile();
	    BufferedWriter out = new BufferedWriter(new FileWriter(f));
	    try
	    {
		out.write(logDocument.getText(0, logDocument.getLength()));
	    }
	    catch (javax.swing.text.BadLocationException e)
	    {
		System.out.println(e);
	    }
	    out.close();
	    return f;
	}
	catch (IOException e)
	{
	    System.out.println(e);
	}
	return null;
    }
    
    public void appendToLog(String str)
    {
	if (logDocument != null)
	{
	    try
	    {
		logDocument.insertString(logDocument.getLength(), str + Local.getNewLine(), null);
	    }
	    catch (BadLocationException e)
	    {}
	}
    };
    
    public String getName()
    {
	return (sourceFile == null ? name : sourceFile.getName()) + " v." + FileVersion;
    }
    
    public void addLeague(League l)
    {
	leagues.add(l);
	setChanged();
	notifyObservers(new ScheduleMsg(ADD, l));
    }
    
    public void renameLeague(League l, String s)
    {
	l.name = s;
	setChanged();
	notifyObservers(new ScheduleMsg(RENAME, l));
    }
    
    public void deleteLeague(int r)
    {
	League lg = (League) leagues.get(r);
	deleteLeague(lg);
    }
    
    public void deleteLeague(League l)
    {
	leagues.removeElement(l);
	setChanged();
	notifyObservers(new ScheduleMsg(DEL, l));
    }
    
    public int getNumberOfLeagues()
    {
	return leagues.size();
    }
    
    public League getLeague(int l)
    {
	return (League) leagues.get(l);
    }
    
    public int findLeague(Object o)
    {
	return leagues.indexOf(o);
    }
    
    public int getNumberOfGames(Facility _f, League _l, Team _t)
    {
	if (_t != null)
	    return _t.getNumberOfGames();
	if (_l != null)
	    return _l.getNumberOfGames();
	if (_f != null)
	    return _f.getNumberOfGames();
	
	int games = 0;
	for (Iterator I = leagues.iterator(); I.hasNext();)
	{
	    League l = (League) I.next();
	    games += l.getNumberOfGames();
	}
	return games;
    }
    
    public Game getGame(int r, Facility _f, League _l, Team _t)
    {
	if (_t != null)
	    return _t.getGame(r);
	if (_f != null)
	    return _f.getGame(r);
	if (_l != null)
	    return _l.getGame(r);
	
	for (Iterator I = leagues.iterator(); I.hasNext();)
	{
	    League l = (League) I.next();
	    if (l.getNumberOfGames() > r)
		return l.getGame(r);
	    else
		r -= l.getNumberOfGames();
	}
	return null;
    }
    
    public League getLeagueFromGame(int r)
    {
	for (Iterator I = leagues.iterator(); I.hasNext();)
	{
	    League l = (League) I.next();
	    if (l.getNumberOfGames() > r)
		return l;
	    else
		r -= l.getNumberOfGames();
	}
	return null;
    }
    
    /*
     * private void alertLeagueListeners(League lg, int event) {
     * if(leagueListeners != null) for(Iterator I =
     * leagueListeners.iterator();I.hasNext();) { ((LeagueChangeListener)
     * (I.next())).LeagueChangeEvent(lg,event);
     * System.out.println("Alerted listener"); } } private void
     * alertFacilityListeners(Facility f, int event) { if(facilityListeners !=
     * null) for(Iterator I = facilityListeners.iterator();I.hasNext();) {
     * ((FacilityChangeListener) (I.next())).FacilityChangeEvent(f,event);
     * System.out.println("Alerted listener"); } }
     */
    public void addFacility(Facility f)
    {
	facilities.add(f);
	for (Iterator I = leagues.iterator(); I.hasNext();)
	{
	    League l = (League) I.next();
	    if (l.facilityCapacity != null)
		l.facilityCapacity.put(f, new Integer(1));
	}
	
	System.out.println("Added facility");
	setChanged();
	notifyObservers(new ScheduleMsg(ADD, f));
	
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, this));
	
	// alertFacilityListeners(f,FacilityChangeListener.ADD);
	
    }
    
    public void deleteFacility(int r)
    {
	Facility f = ((Facility) facilities.get(r));
	facilities.removeElementAt(r);
	setChanged();
	notifyObservers(new ScheduleMsg(DEL, f));
	// alertFacilityListeners(f,FacilityChangeListener.DEL);
    }
    
    public void deleteFacility(Facility f)
    {
	facilities.removeElement(f);
	setChanged();
	notifyObservers(new ScheduleMsg(DEL, f));
    }
    
    public int getNumberOfFacilities()
    {
	return facilities.size();
    }
    
    public int getIndexOfFacility(Object o)
    {
	return facilities.indexOf(o);
    }
    
    public String getFacilityName(int r)
    {
	return ((Facility) facilities.get(r)).name;
    }
    
    public void setFacilityName(int r, String _name)
    {
	Facility f = ((Facility) facilities.get(r));
	setFacilityName(f, _name);
    }
    
    public void setFacilityName(Facility f, String _name)
    {
	f.name = _name;
	setChanged();
	notifyObservers(new ScheduleMsg(RENAME, f));
    }
    
    public Integer getFacilityPref(League l, int f)
    {
	if (l == null)
	    return null;
	return (Integer) l.facilityPref.get(getFacility(f));
    }
    
    public Integer getFacilityCap(League l, int f)
    {
	if (l == null)
	    return null;
	return (Integer) l.facilityCapacity.get(getFacility(f));
    }
    
    public void setFacilityPref(League l, int f, Integer val)
    {
	Facility fac = getFacility(f);
	l.facilityPref.remove(fac);
	l.facilityPref.put(fac, val);
    }
    
    public void setFacilityCap(League l, int f, Integer val)
    {
	Facility fac = getFacility(f);
	l.facilityCapacity.remove(fac);
	l.facilityCapacity.put(fac, val);
    }
    
    public Facility getFacility(int j)
    {
	return (Facility) facilities.get(j);
    }
    
    public int findFacility(Object o)
    {
	return facilities.indexOf(o);
    }
    
    public void clearSchedule()
    {
	for (Iterator I = leagues.iterator(); I.hasNext();)
	    ((League) I.next()).clearSchedule();
	
	for (Iterator I = facilities.iterator(); I.hasNext();)
	    ((Facility) I.next()).initialize();
	
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, this));
	
	clearAlarmSystem(null);
	
    }
    
    public void schedule()
    {
	for (Iterator I = leagues.iterator(); I.hasNext();)
	    ((League) I.next()).createGames();
	
	Vector lrank = (Vector) leagues.clone();
	Collections.sort(lrank, new Comparator()
	{
	    public int compare(Object o1, Object o2)
	    {
		Integer l1 = ((League) o1).possibilities();
		Integer l2 = ((League) o2).possibilities();
		return l1.compareTo(l2);
	    }
	});
	
	System.out.println("Scheduling order: ");
	
	for (Iterator I = lrank.iterator(); I.hasNext();)
	    System.out.println(((League) I.next()).getName());
	
	for (Iterator I = facilities.iterator(); I.hasNext();)
	    ((Facility) I.next()).initialize();
	
	for (Iterator I = lrank.iterator(); I.hasNext();)
	{
	    // League lg = ((League) I.next());
	    // if(lg.name.matches("A")) lg.schedule(this);
	    ((League) I.next()).schedule(this);
	}
	
	for (Iterator I = facilities.iterator(); I.hasNext();)
	{
	    Facility f = ((Facility) I.next());
	    appendToLog("Availability for " + f.getName());
	    f.logAvailability(this);
	    appendToLog("-----------------------------------");
	}
	
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, this));
	populateAlarmSystem(null);
    }
    
    /*
     * Filling the Database with Game entries
     */
    private void populateAlarmSystem(String user)
    {
	// AlarmSystem alarm = new AlarmSystem(user);
    control = new RSMSController();
    AlarmSystem alarm = new AlarmSystem(control.getCurUser().getUsername()+"_"+control.getCurSport());
    for (Iterator I = leagues.iterator(); I.hasNext();)
	{
	    League l = (League) I.next();
	    for (Iterator J = l.games.iterator(); J.hasNext();)
	    {
		Game g = (Game) J.next();
		try
		{
		    alarm.addNotice(new Notice(g.getStartDate(), g.getEndDate(), g.toString(),
					       "game"));
		}
		catch (Exception e)
		{
		    // pass
		}
	    }
	}
	alarm.disconnectFromDB();
    }
    
    /*
     * Clear the databse of game entries
     */
    private void clearAlarmSystem(String user)
    {
	// AlarmSystem alarm = new AlarmSystem(user);
	AlarmSystem alarm = new AlarmSystem("Ben");
	alarm.removeAllNotices();
	alarm.disconnectFromDB();
    }
    
    /*
     * Add a single game entry to the database
     */

    private void addGameToAlarmSystem(Game game)
    {
	// AlarmSystem alarm = new AlarmSystem(user);
	AlarmSystem alarm = new AlarmSystem("Ben");
	try
	{
	    alarm.addNotice(new Notice(game.getStartDate(), game.getEndDate(), game.toString(),
				       "game"));
	}
	catch (Exception e)
	{
	    // pass
	}
	finally
	{
	    alarm.disconnectFromDB();
	}
    }
    
    /*
     * Remove a single game entry from the databse
     */

    private void removeGameFromAlarmSystem(Game game)
    {
	// AlarmSystem alarm = new AlarmSystem(user);
	AlarmSystem alarm = new AlarmSystem("Ben");
	try
	{
	    alarm.removeNotice(new Notice(game.getStartDate(), game.getEndDate(), game.toString(),
					  "game"));
	}
	catch (Exception e)
	{
	    // pass
	}
	finally
	{
	    alarm.disconnectFromDB();
	}
    }
    
    public DefaultStyledDocument getLogDocument()
    {
	return logDocument;
    }
    
    public void clearLog()
    {
	try
	{
	    logDocument.remove(0, logDocument.getLength() - 1);
	}
	catch (Exception e)
	{
	    ;
	} // e.print();}
	
    }
    
    private void writeObject(java.io.ObjectOutputStream out) throws IOException
    {
	try
	{
	    logString = logDocument.getText(0, logDocument.getLength() - 1);
	}
	catch (javax.swing.text.BadLocationException e)
	{
	    System.out.println(e);
	}
	out.defaultWriteObject();
    }
    
    private void readObject(java.io.ObjectInputStream in) throws IOException,
							 ClassNotFoundException
    {
	in.defaultReadObject();
	logDocument = new DefaultStyledDocument();
	appendToLog(logString);
	
    }
    
    public void updateScheduleTree()
    {
	setChanged();
	notifyObservers(new ScheduleMsg(SCHEDULE_CHANGED, this));
    }
    
    public AutoScheduleDoc()
    {
	name = "schedule";
	leagues = new Vector();
	facilities = new Vector();
	facilities.add(new Facility("ISB"));
	logDocument = new DefaultStyledDocument();
	appendToLog("Date: " + (new Date()) + autoteam.Local.getNewLine());
    }
    
    static final long serialVersionUID = -7100344554333703528L;
}
